<?php

namespace app\data\driver;

use Exception;
use think\facade\Env;

class Cache
{
  protected \Redis $cache;
  protected string $hostname;
  protected string $password;
  protected int $port;
  protected int $timeout;
  protected string $prefix;
  protected int $expired;
  private static ?Cache $_instance = NULL;

  private function __construct(){
    $this->hostname = Env::get('redis.hostname');
    $this->password = Env::get('redis.password');
    $this->port = Env::get('redis.port');
    $this->timeout = Env::get('redis.timeout');
    $this->prefix = Env::get('redis.prefix');
    $this->expired = Env::get('redis.expired');
    $this->cache = new \Redis();
    $this->cache->connect($this->hostname,$this->port,$this->timeout);
    $this->cache->auth($this->password);
    $this->cache->setOption($this->cache::OPT_PREFIX,$this->prefix);
    $this->cache->select(0);
  }


  /**
   *
   * title
   *
   * @throws Exception
   */
  private function __clone(){
    // TODO: Implement __clone method.
  }

  /**
   *
   * title
   *
   * @throws Exception
   */
  private function __wakeup(){
    // TODO: Implement __wakeup method.
  }

  private function __sleep(): array
  {
    // TODO: Implement __sleep() method.
  }

  public static function getInstance(): ?Cache
  {
    if(empty(self::$_instance)){
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  public function getObject(): \Redis
  {
    return $this->cache;
  }

  public function __destruct(){
    self::$_instance = NULL;
  }
}
